package com.sgj.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.sgj.common.constant.ProductConstant;
import com.sgj.common.es.SkuEsModel;
import com.sgj.common.es.SkuEsModel.Attrs;
import com.sgj.common.vo.SkuHasStockVo;
import com.sgj.common.to.SkuReductionTo;
import com.sgj.common.to.SpuBoundsTo;
import com.sgj.common.utils.R;
import com.sgj.gulimall.product.entity.*;
import com.sgj.gulimall.product.feign.CouponFeignService;
import com.sgj.gulimall.product.feign.SearchFeignService;
import com.sgj.gulimall.product.feign.WareFeignService;
import com.sgj.gulimall.product.service.*;
import com.sgj.gulimall.product.vo.SpuSaveVo;
import com.sgj.gulimall.product.vo.SpuSaveVo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sgj.common.utils.PageUtils;
import com.sgj.common.utils.Query;

import com.sgj.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    public static final String CONSTANT = "0";

    // 热度评分，默认0
    public static final Long HOTSCORE = 0L;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService attrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );
        return new PageUtils(page);
    }

    // @GlobalTransactional
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 保存spu基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        // 保存spu的描述图片
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = SpuInfoDescEntity.builder()
                .spuId(spuInfoEntity.getId())
                .decript(String.join(",", decript))
                .build();
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        // 保存spu的图片集
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        // 保存spu的规格参数
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> attrValueEntities = baseAttrs.stream().map(attr -> {
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            return ProductAttrValueEntity.builder()
                    .attrId(attr.getAttrId())
                    .attrName(Objects.nonNull(attrEntity) ? (Objects.nonNull(attrEntity.getAttrName()) ? attrEntity.getAttrName() : null) : null)
                    .attrValue(attr.getAttrValues())
                    .quickShow(attr.getShowDesc())
                    .spuId(spuInfoEntity.getId())
                    .build();
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(attrValueEntities);

        // 保存spu的积分信息
        SpuBoundsTo spuBoundsTo = SpuBoundsTo.builder()
                .spuId(spuInfoEntity.getId())
                .buyBounds(spuSaveVo.getBounds().getBuyBounds())
                .growBounds(spuSaveVo.getBounds().getGrowBounds())
                .build();
        R spuBounds = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (spuBounds.getCode() != 0) {
            log.error("远程调用保存积分信息失败");
        }

        // 保存当前spu对应的所有sku信息
        List<Skus> skus = spuSaveVo.getSkus();
        if (!CollectionUtils.isEmpty(skus) && skus.size() > 0) {
            skus.forEach(item -> {
                // List<Integer> defaultImg = item.getImages().stream()
                //         .filter(image -> image.getDefaultImg() == 1)
                //         .map(Images::getDefaultImg)
                //         .collect(Collectors.toList());

                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = SkuInfoEntity.builder()
                        .spuId(spuInfoEntity.getId())
                        .skuName(item.getSkuName())
                        .catalogId(spuInfoEntity.getCatalogId())
                        .brandId(spuInfoEntity.getBrandId())
                        .skuDefaultImg(defaultImg)
                        .skuTitle(item.getSkuTitle())
                        .skuSubtitle(item.getSkuSubtitle())
                        .price(item.getPrice())
                        .saleCount(0L)
                        .build();
                // 保存sku的基本信息
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = SkuImagesEntity.builder()
                            .skuId(skuId)
                            .imgUrl(img.getImgUrl())
                            .defaultImg(img.getDefaultImg())
                            .build();
                    return skuImagesEntity;
                }).filter(entity -> StringUtils.isNotBlank(entity.getImgUrl()))
                .collect(Collectors.toList());
                // TODO 没有图片的路径无需保存
                // 保存sku的图片信息
                skuImagesService.saveBatch(skuImagesEntities);

                // 保存sku的销售属性信息
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // 保存sku的优惠、满减等信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 &&
                        skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) == 1) {
                    R skuReduction = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (skuReduction.getCode() != 0) {
                        log.error("远程调用保存优惠、满减信息失败");
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        String status = (String) params.get("status");
        String brandId = (String) params.get("brandId");
        String catalogId = (String) params.get("catelogId");

        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(item -> item.eq("id", key).or().like("spu_name", key));
        }

        if (StringUtils.isNotEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        if (StringUtils.isNotEmpty(brandId) && !CONSTANT.equalsIgnoreCase(catalogId)) {
            wrapper.eq("brand_id", brandId);
        }

        if (StringUtils.isNotEmpty(catalogId) && !CONSTANT.equalsIgnoreCase(catalogId)) {
            wrapper.eq("catalog_id", catalogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        // 查出当前 spuid 对应的所有 sku 信息，品牌名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        // 查询当前 sku 的所有可以被检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = attrValueService.baseListForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream()
                .map(ProductAttrValueEntity::getAttrId)
                .collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);

        Set<Long> idSet = new HashSet<>(searchAttrIds);

        List<Attrs> attrsList = baseAttrs.stream()
                .filter(item -> idSet.contains(item.getAttrId()))
                .map(item -> {
                    Attrs attrs1 = new Attrs();
                    BeanUtils.copyProperties(item, attrs1);
                    return attrs1;
                })
                .collect(Collectors.toList());

        // 获取所有 skuId
        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        // 发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> stockMap = new HashMap<>();
        try {
            R r = wareFeignService.getSkusHasStock(skuIdList);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>(){};
            // JSONObject jsonObj = new JSONObject(skusHasStock);
            // // 由于转换过来的数据为 = 不能转换为对象，所以需要替换一下
            // String data = jsonObj.getString("data").replace("=", ":");
            // List<SkuHasStockVo> skuHasStockVos = JSONObject.parseArray(data, SkuHasStockVo.class);
            stockMap = r.getData(typeReference).stream()
                    .collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常,原因：{}", e);
        }

        // 封装每个 sku 的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            // 查询品牌和分类的名称信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());

            // 组装需要的数据
            SkuEsModel esModel = SkuEsModel.builder()
                    .skuId(sku.getSkuId())
                    .spuId(sku.getSpuId())
                    .skuTitle(sku.getSkuTitle())
                    .skuPrice(sku.getPrice())
                    .skuImg(sku.getSkuDefaultImg())
                    .saleCount(sku.getSaleCount())
                    .hasStock(Objects.isNull(finalStockMap) ? true : finalStockMap.get(sku.getSkuId()))
                    .hotScore(HOTSCORE)
                    .brandId(sku.getBrandId())
                    .catalogId(sku.getCatalogId())
                    .brandName(brandEntity.getName())
                    .brandImg(brandEntity.getLogo())
                    .catalogName(categoryEntity.getName())
                    .attrs(attrsList)
                    .build();
            return esModel;
        }).collect(Collectors.toList());

        // 将数据存入 es, gulimall-search 模块
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode() == 0) {
            // 远程调用成功
            // 修改当前 spu 状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            // 远程调用失败
            // TODO 重复调用、接口幂等性、重试机制
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfo = skuInfoService.getById(skuId);
        return getById(skuInfo.getSpuId());
    }
}